<template>
  <el-main>
    <el-card>
      <template #header>
        <div class="card-header">
          <span>菜单管理</span>
          <div>
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>
              添加菜单
            </el-button>
            <el-button type="danger" @click="handleBatchDelete" :disabled="selectedKeys.length === 0">
              <el-icon><Delete /></el-icon>
              批量删除
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form
        ref="searchRef"
        :model="searchParam"
        :inline="true"
        class="search-form"
      >
        <el-form-item label="菜单名称" prop="menuName">
          <el-input
            v-model="searchParam.param.menuName"
            placeholder="请输入菜单名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="菜单编码" prop="menuCode">
          <el-input
            v-model="searchParam.param.menuCode"
            placeholder="请输入菜单编码"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="菜单类型" prop="menuType">
          <el-select
            v-model="searchParam.param.menuType"
            placeholder="请选择菜单类型"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="option in MENU_TYPE_OPTIONS"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="searchParam.param.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option
              v-for="option in MENU_STATUS_OPTIONS"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 树形表格 -->
      <el-table
        ref="tableRef"
        :data="filteredMenuTree"
        v-loading="loading"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        :default-expand-all="false"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="menuCode" label="菜单编码" width="150" />
        <el-table-column prop="menuName" label="菜单名称" width="150" />
        <el-table-column prop="displayName" label="菜单显示名称" width="180" />
        <el-table-column prop="menuType" label="菜单类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getMenuTypeTagType(row.menuType)">
              {{ getMenuTypeLabel(row.menuType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="path" label="路由路径" width="200" show-overflow-tooltip />
        <el-table-column prop="component" label="组件路径" width="200" show-overflow-tooltip />
        <el-table-column prop="icon" label="图标" width="100">
          <template #default="{ row }">
            <el-icon v-if="row.icon">
              <component :is="row.icon" />
            </el-icon>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleAddChild(row)">
              添加子菜单
            </el-button>
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 菜单表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="菜单编码" prop="menuCode">
          <el-input v-model="formData.menuCode" placeholder="请输入菜单编码" />
        </el-form-item>
        <el-form-item label="菜单名称" prop="menuName">
          <el-input v-model="formData.menuName" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item label="菜单显示名称" prop="displayName">
          <el-input v-model="formData.displayName" placeholder="请输入菜单显示名称" />
        </el-form-item>
        <el-form-item label="菜单类型" prop="menuType">
          <el-radio-group v-model="formData.menuType">
            <el-radio
              v-for="option in MENU_TYPE_OPTIONS"
              :key="option.value"
              :label="option.value"
            >
              {{ option.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="父级菜单" prop="parentId">
          <el-tree-select
            v-model="formData.parentId"
            :data="menuOptions"
            :props="treeProps"
            placeholder="请选择父级菜单"
            check-strictly
            clearable
          />
        </el-form-item>
        <el-form-item label="路由路径" prop="path" v-if="formData.menuType !== 3">
          <el-input v-model="formData.path" placeholder="请输入路由路径" />
        </el-form-item>
        <el-form-item label="组件路径" prop="component" v-if="formData.menuType === 2">
          <el-input v-model="formData.component" placeholder="请输入组件路径" />
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-input v-model="formData.icon" placeholder="请输入图标名称" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio
              v-for="option in MENU_STATUS_OPTIONS"
              :key="option.value"
              :label="option.value"
            >
              {{ option.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </el-main>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus';
import { Plus, Delete, Search, Refresh } from '@element-plus/icons-vue';
import { 
  getMenuTree, 
  addMenu, 
  updateMenu, 
  deleteMenu, 
  deleteMenus,
  getMenuOptions 
} from '@/api/menu';
import type { Menu, MenuQuery, MenuForm } from '@/api/menu/MenuModel';
import { MENU_TYPE_OPTIONS, MENU_STATUS_OPTIONS } from '@/api/menu/MenuModel';

// 响应式数据
const tableRef = ref();
const searchRef = ref<FormInstance>();
const formRef = ref<FormInstance>();

// 菜单数据
const menuTree = ref<Menu[]>([]);
const menuOptions = ref<Menu[]>([]);
const loading = ref(false);

// 搜索参数
const searchParam = reactive<MenuQuery>({
  curPage: 1,
  pageSize: 10,
  total: 0,
  pages: 0,
  param: {
    menuName: '',
    menuCode: '',
    menuType: undefined,
    status: undefined
  }
});

// 选中的行
const selectedKeys = ref<number[]>([]);

// 对话框
const dialogVisible = ref(false);
const dialogTitle = ref('');
const submitLoading = ref(false);

// 表单数据
const formData = reactive<MenuForm>({
  menuCode: '',
  menuName: '',
  displayName: '',
  menuType: 1,
  parentId: null,
  level: 1,
  sort: 0,
  path: '',
  component: '',
  icon: '',
  status: 1,
  remark: ''
});

// 树形选择器配置
const treeProps = {
  children: 'children',
  label: 'displayName',
  value: 'id'
};

// 表单验证规则
const formRules = {
  menuCode: [
    { required: true, message: '请输入菜单编码', trigger: 'blur' }
  ],
  menuName: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' }
  ],
  displayName: [
    { required: true, message: '请输入菜单显示名称', trigger: 'blur' }
  ],
  menuType: [
    { required: true, message: '请选择菜单类型', trigger: 'change' }
  ],
  sort: [
    { required: true, message: '请输入排序', trigger: 'blur' }
  ]
};

// 过滤后的菜单树
const filteredMenuTree = computed(() => {
  if (!searchParam.param.menuName && 
      !searchParam.param.menuCode && 
      searchParam.param.menuType === undefined && 
      searchParam.param.status === undefined) {
    return menuTree.value;
  }
  
  return filterMenuTree(menuTree.value);
});

// 递归过滤菜单树
const filterMenuTree = (menus: Menu[]): Menu[] => {
  return menus.filter(menu => {
    const matches = 
      (!searchParam.param.menuName || menu.menuName.includes(searchParam.param.menuName)) &&
      (!searchParam.param.menuCode || menu.menuCode.includes(searchParam.param.menuCode)) &&
      (searchParam.param.menuType === undefined || menu.menuType === searchParam.param.menuType) &&
      (searchParam.param.status === undefined || menu.status === searchParam.param.status);
    
    if (menu.children && menu.children.length > 0) {
      const filteredChildren = filterMenuTree(menu.children);
      if (filteredChildren.length > 0) {
        return { ...menu, children: filteredChildren };
      }
    }
    
    return matches;
  });
};

// 获取菜单类型标签类型
const getMenuTypeTagType = (menuType: number) => {
  const typeMap = {
    1: 'primary',
    2: 'success',
    3: 'warning'
  };
  return typeMap[menuType as keyof typeof typeMap] || 'info';
};

// 获取菜单类型标签
const getMenuTypeLabel = (menuType: number) => {
  const option = MENU_TYPE_OPTIONS.find(opt => opt.value === menuType);
  return option?.label || '未知';
};

// 获取菜单树
const loadMenuTree = async () => {
  try {
    loading.value = true;
    const response = await getMenuTree();
    menuTree.value = response.data || [];
  } catch (error) {
    ElMessage.error('获取菜单树失败');
  } finally {
    loading.value = false;
  }
};

// 获取菜单选项
const loadMenuOptions = async () => {
  try {
    const response = await getMenuOptions();
    menuOptions.value = response.data || [];
  } catch (error) {
    ElMessage.error('获取菜单选项失败');
  }
};

// 搜索
const handleSearch = () => {
  // 过滤逻辑在computed中处理
};

// 重置
const handleReset = () => {
  searchRef.value?.resetFields();
  // 手动重置搜索参数
  searchParam.param.menuName = '';
  searchParam.param.menuCode = '';
  searchParam.param.menuType = undefined;
  searchParam.param.status = undefined;
};

// 选择改变
const handleSelectionChange = (selection: Menu[]) => {
  selectedKeys.value = selection.map(item => item.id);
};

// 添加菜单
const handleAdd = () => {
  dialogTitle.value = '添加菜单';
  resetForm();
  formData.parentId = null;
  formData.level = 1;
  dialogVisible.value = true;
};

// 添加子菜单
const handleAddChild = (data: Menu) => {
  dialogTitle.value = '添加子菜单';
  resetForm();
  formData.parentId = data.id;
  formData.level = data.level + 1;
  dialogVisible.value = true;
};

// 编辑菜单
const handleEdit = (data: Menu) => {
  dialogTitle.value = '编辑菜单';
  Object.assign(formData, data);
  dialogVisible.value = true;
};

// 删除菜单
const handleDelete = async (data: Menu) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除菜单"${data.displayName}"吗？删除后不可恢复！`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    await deleteMenu(data.id);
    ElMessage.success('删除成功');
    await loadMenuTree();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
    }
  }
};

// 批量删除
const handleBatchDelete = async () => {
  if (selectedKeys.value.length === 0) {
    ElMessage.warning('请选择要删除的菜单');
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedKeys.value.length} 个菜单吗？删除后不可恢复！`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    await deleteMenus(selectedKeys.value);
    ElMessage.success('批量删除成功');
    selectedKeys.value = [];
    await loadMenuTree();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败');
    }
  }
};

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    menuCode: '',
    menuName: '',
    displayName: '',
    menuType: 1,
    parentId: null,
    level: 1,
    sort: 0,
    path: '',
    component: '',
    icon: '',
    status: 1,
    remark: ''
  });
  formRef.value?.clearValidate();
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    submitLoading.value = true;
    
    if (formData.id) {
      await updateMenu(formData);
      ElMessage.success('更新成功');
    } else {
      await addMenu(formData);
      ElMessage.success('添加成功');
    }
    
    dialogVisible.value = false;
    await loadMenuTree();
  } catch (error) {
    ElMessage.error(formData.id ? '更新失败' : '添加失败');
  } finally {
    submitLoading.value = false;
  }
};

// 初始化
onMounted(() => {
  loadMenuTree();
  loadMenuOptions();
});
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 16px;
}

:deep(.el-table .el-table__row) {
  cursor: pointer;
}

:deep(.el-table .el-table__row:hover) {
  background-color: var(--el-table-row-hover-bg-color);
}
</style>